package ge.telasi.tasks.ui.comp;

import ge.telasi.tasks.ui.log.LoggableField;
import ge.telasi.tasks.ui.log.Logger;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 * @author dimitri
 */
public class SuggestionTextArea extends JTextArea implements LoggableField {
    private String suggestion;
    private Exception exception;
    private Logger logger;

    public SuggestionTextArea() {
        getDocument().addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                onTextChanged();
            }

            public void removeUpdate(DocumentEvent e) {
                onTextChanged();
            }

            public void changedUpdate(DocumentEvent e) {
                onTextChanged();
            }
        });
    }

    private void onTextChanged() {
        setException(null);
        if (logger != null) {
            logger.clear();
        }
    }

    public String getSuggestion() {
        return suggestion;
    }

    public void setSuggestion(String suggestion) {
        this.suggestion = suggestion;
        if (getToolTipText() == null || getToolTipText().length() == 0) {
            setToolTipText(suggestion);
        }
        repaint();
    }

    public Exception getException() {
        return exception;
    }

    public void setException(Exception exception) {
        this.exception = exception;
        repaint();
    }

    public Logger getLogger() {
        return logger;
    }

    public void setLogger(Logger logger) {
        this.logger = logger;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        paintSuggestion(g2d);
        paintError(g2d);
    }

    private void paintSuggestion(Graphics2D g2d) {
        boolean hasSuggestion = suggestion != null && suggestion.length() > 0;
        boolean hasText = getText() != null && getText().length() > 0;
        if (hasSuggestion && !hasText) {
            int width = getWidth();
//            int height = getHeight();
            PaintUtils.paintSuggestion(g2d, suggestion, width, 25);
        }
    }

    private void paintError(Graphics2D g2d) {
        if (exception != null) {
            int width = getWidth();
//            int height = getHeight();
            PaintUtils.paintError(g2d, width, 25);
        }
    }
}
